# Copyright (c) 2024-present AI-Labs

import json
import time

import requests

from comps import (
    Base64ByteStrDoc,
    CustomLogger,
    ServiceType,
    TextDoc,
    opea_microservices,
    register_microservice,
    register_statistics,
    statistics_dict,
)

from configs import config

logger = CustomLogger("opea_service@tts")
logflag = config.opea_service.tts.logs

"""
注册微服务
"""
@register_microservice(
    name="opea_service@tts",
    service_type=ServiceType.TTS,
    host=config.opea_service.tts.host,
    port=config.opea_service.tts.port,
    endpoint="/v1/audio/speech",
    input_datatype=TextDoc,
    output_datatype=Base64ByteStrDoc,
)

# 微服务的具体处理逻辑
@register_statistics(names=["opea_service@tts"])
async def text_to_audio(input: TextDoc):
    start = time.time()
    text = input.text
    inputs = {"text": text}
    if logflag:
        logger.info(f"接收到用户请求：{inputs}")

    # 请求底层基础功能进行语音转换处理
    response = requests.post(url=f"{config.opea_service.tts.endpoint}/tts/melotts/v1", data=json.dumps(inputs), proxies={"http": None})
    
    # 统计耗时
    statistics_dict["opea_service@tts"].append_latency(time.time() - start, None)

    if logflag:
        logger.info(f"接收到处理结果：{response}")

    # 返回响应结果
    return Base64ByteStrDoc(byte_str=response.json()["tts_result"])

"""
启动微服务
"""
def start():
    opea_microservices["opea_service@tts"].start()

if __name__ == "__main__":
    start()
